package com.banciyuan.bcywebview.biz.main.mineinfo.reward;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.GiftApi;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.LoadingHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.GiftPostData;
import de.greenrobot.daoexample.model.MyGiftItem;

/**
 * Created by hy on 2016/5/16.
 */
public class SendFeedFragment extends BaseLazyContainerFragment {
    private ListView mListView;
    private RequestQueue mQueue;
    private List<MyGiftItem> mMyGiftItems = new ArrayList<>();
    private RewardAdapter mAdapter;
    private int page = 1;
    private boolean mLastItemVisible = false;
    private boolean loading = false;
    private boolean end_flag = false;
    private LoadingHelper mProgressbarHelper;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.sendfeed_fragment_layout, container, false);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarHelper = new LoadingHelper(rootview);
        mProgressbarHelper.setActionCallbacks(new LoadingHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                if (mProgressbarHelper.getState() == LoadingHelper.PROGRESS_STATE_FAILED) {
                    mProgressbarHelper.onLoading();
                    initData();
                }
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        mListView = (ListView) rootview.findViewById(R.id.lv);
    }

    @Override
    protected void initAction() {
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int state) {
                if (state == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && mLastItemVisible) {
                    if (!loading) {
                        if (!end_flag) {
                            page++;
                            loading = true;
                            initData();
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                mLastItemVisible = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1);
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GiftPostData postData = mMyGiftItems.get(position).getPost_data();
                if (!postData.isPost_del())
                    switch (postData.getType()) {
                        case "cos":
                            DetailDataHelper.gotoCosDetail(getActivity(), postData.getRp_id(), postData.getCp_id(), false);
                            break;
                        case "illust":
                            DetailDataHelper.gotoDrawerDetail(getActivity(), postData.getRp_id(), postData.getDp_id(), false);
                            break;
                        case "novel":
                            DetailDataHelper.gotoWriterDetail(getActivity(), postData.getRp_id(), postData.getWp_id(), false);
                            break;
                        case "daily":
                            DetailDataHelper.gotoDailyDetail(getActivity(), postData.getUd_id(), false);
                            break;
                    }
            }
        });
    }

    @Override
    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        paramsList.add(new BcyPair(HttpUtils.PAGE, page + ""));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + GiftApi.getListSendGifts();
        Response.Listener onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                    try {
                        JSONObject result = new JSONObject(s);
                        Gson gson = new Gson();
                        List<MyGiftItem> tempGiftItems = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA),
                                new TypeToken<List<MyGiftItem>>() {
                                }.getType());
                        popIllegalData(tempGiftItems);
                        processData(tempGiftItems);
                        if (page == 1 && tempGiftItems.size() == 0) {
                            mProgressbarHelper.onNodata("", true);
                        }
                    } catch (Exception e) {
                        mProgressbarHelper.onFailed();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };
        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), params);
        StringRequest stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSucc, onErrorProxy);
        mQueue.add(stringRequest);
    }

    private void popIllegalData(List<MyGiftItem> tempGiftItems) {
        List<MyGiftItem> illegalData = new ArrayList<>();
        for (MyGiftItem tempGiftItem : tempGiftItems) {
            if (!tempGiftItem.getPost_data().isPost_del() && TimelineFactory.illegalFeedType(tempGiftItem.getPost_data().getType()))
                illegalData.add(tempGiftItem);
        }
        tempGiftItems.removeAll(illegalData);
    }

    private void processData(List<MyGiftItem> tempGiftItems) {
        end_flag = null == tempGiftItems || tempGiftItems.size() == 0;
        mMyGiftItems.addAll(tempGiftItems);
        if (null == mAdapter) {
            mAdapter = new RewardAdapter(getActivity(), mMyGiftItems, 0);
            mListView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        loading = false;
        mProgressbarHelper.onSuccess();
    }

}
